<template>
    <div class="iotdevice-list" v-if="permission['iotdevice_view']">
        <basic-container class="left">
            <el-input v-model="filterText" class="w-60 mb-2" placeholder="请输入" />
            <h4>公司信息</h4>
            <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="treeData" :props="defaultProps"
                default-expand-all :filter-node-method="filterNode" @node-click="selectTree" />
        </basic-container>
        <basic-container class="right">
            <!-- 顶部搜索框 -->
            <el-space wrap>
                <el-input v-model="search" style="width: 240px" placeholder="请输入" />
                <el-button type="primary" :icon="Search" @click="getDevices">搜索</el-button>
                <el-button type="primary" :icon="Plus" title="新增" @click="addModelShow = true"
                    v-if="permission['iotdevice_add']">新增</el-button>
                <el-button :icon="Delete" title="删除" type="danger" plain @click="deleteData()"
                    v-if="permission['iotdevice_delete']">删除</el-button>
            </el-space>
            <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%;margin-top: 30px;"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property="deviceCode" label="设备编码" width="120" />
                <el-table-column property="address" label="安装位置" width="120" />
                <el-table-column property="状态" label="状态">
                    <template #default="scope">
                        <!-- 状态1:未激活;2在线;3离线;4故障 -->
                        {{ scope.row.switchStatus === 3 ? '高' :
                            scope.row.switchStatus === 2 ? '中' :
                                scope.row.switchStatus === 1 ? '低' :
                                    scope.row.switchStatus === 0 ? '关' : '关'
                        }}
                    </template>
                </el-table-column>
                <!-- TODO:  -->
                <el-table-column property="控制" label="控制">
                    <template #default="scope">
                        <el-button-group v-if="functionDropdown.length">
                            <el-button v-for="item of functionDropdown[0]['enums']"
                                :type="scope.row.switchStatus === Number(item.id) ? 'success' : 'primary'"
                                @click="stateChange(scope.row, item)">{{ item.label }}</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" :icon="View" link @click="look(scope.row)">查看</el-button>
                        <el-button type="primary" :icon="Edit" link @click="edit(scope.row)"
                            v-if="permission['iotdevice_edit']">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 40]" :background="true" :total="totalPage"
                    layout="total, sizes, prev, pager, next, jumper" :hide-on-single-page="false"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 10px;" />
            </div>
        </basic-container>

        <el-dialog v-model="addModelShow" :title="addFromItem ? '编辑设备' : '添加设备'" width="1200" :footer="false">
            <IotdeviceAdd :options="treeData" :fromItem="addFromItem" @clearAdd="clearAdd" @submitAdd="submitAdd"
                v-if="addModelShow">
            </IotdeviceAdd>
        </el-dialog>

        <el-dialog v-model="detailsModelShow" title="设备信息" width="1200" :footer="false">
            <IotdeviceDetails :fromItem="addFromItem" v-if="detailsModelShow"></IotdeviceDetails>
        </el-dialog>

    </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { getLeftTree, getDeviceList, add, update, remove, deviceControl } from "@/api/desk/iotdevice";
import { getFunctionDropdown } from "@/api/desk/iotrules";
import { Plus, Delete, View, Edit, Search } from '@element-plus/icons-vue'
import type { TreeInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import IotdeviceAdd from './components/iotdeviceAdd.vue'
import IotdeviceDetails from './components/iotdeviceDetails.vue'

const store = useStore()

const permission = computed(() => store.getters.permission)

interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'title'
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.title.includes(value)
}
// 添加编辑弹框的现实状态
const addModelShow = ref(false)
// 显示详情的弹框
const detailsModelShow = ref(false)

// 左侧树结构
const treeData = ref([])
// 点击左侧树结构
const treeId = ref(null)

// 点击左侧树结构
const selectTree = (e) => {
    treeId.value = e.id
    getDevices()
}

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalPage = ref(0)
// 搜索框
const search = ref('')
// 列表数据
const tableData = ref()
const multipleSelection = ref([])
// 列表复选框
const handleSelectionChange = (val) => {
    multipleSelection.value = val.map(item => item.id);
}
// 删除
const deleteData = () => {
    if (!multipleSelection.value.length) {
        return
    }
    ElMessageBox.confirm(
        '确认删除这些设备吗?',
        '确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            remove(multipleSelection.value.join(',')).then((res) => {
                ElMessage({
                    type: 'success',
                    message: '已成功删除',
                })
                getDevices()
            })

        })
}




// 获取设备列表
const getDevices = () => {
    getDeviceList({
        treeId: treeId.value,
        deviceCode: '',
        current: currentPage.value,
        size: pageSize.value,
        search: search.value // TODO: 接口缺少模糊搜索参数
    }).then((res) => {
        totalPage.value = res.data.data.total
        tableData.value = res.data.data.records
    })
}

// 获取左侧树结构
const getTreeList = () => {
    getLeftTree().then((res) => {
        treeData.value = res.data.data
        treeId.value = treeData.value[0]['id']
        getDevices()
    })
}

// 分页
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getDevices()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getDevices()
}
const functionDropdown = ref()
const getEnum = (str) => {
    return str.split(';').map(item => {
        const [label, id] = item.split(':');
        return {
            id: id?.trim(),
            label: label?.trim()
        };
    }).filter(item => item.id && item.label);
}
// 获取功能列表
const getFunctionDropdowns = () => {
    getFunctionDropdown().then((res) => {
        functionDropdown.value = res.data.data.map((item) => {
            if (item.fieldType === 'enum') {
                item.enums = getEnum(item.specEnum)
            }
            return item
        }).filter(item => item.functionCode === 'switchStatus')
    })
}

getFunctionDropdowns()
getTreeList()

// 状态改变
const stateChange = (electron, item) => {
    electron.switchStatus = Number(item.id)
    deviceControl({
        deviceId: electron.id,
        deviceCode: electron.deviceCode,
        attributeCode: functionDropdown.value[0]?.functionCode,
        value: electron.switchStatus
    }).then((res) => {
        ElMessage({
            type: 'success',
            message: '已成功修改',
        })
    })
}
const addFromItem = ref(null)
// 查看
const look = (item) => {
    console.log(item)
    addFromItem.value = item
    detailsModelShow.value = true
}
// 关闭查看
const clearAdd = () => {
    addFromItem.value = null
    addModelShow.value = false
}
// 添加/编辑
const submitAdd = (from) => {
    if (from.id) {
        // 编辑
        update({
            id: from.id,
            deviceCode: from.deviceCode,
            longitude: from.longitude,
            dimension: from.dimension,
            address: from.address,
            deptId: from.deptId,
        }).then((res) => {
            ElMessage({
                message: res.data.msg,
                type: 'success'
            })
            clearAdd()
            getDevices()
        })
    } else {
        // 添加
        add({
            id: from.id || null,
            deviceCode: from.deviceCode,
            longitude: from.longitude,
            dimension: from.dimension,
            address: from.address,
            deptId: from.deptId,
        }).then((res) => {
            ElMessage({
                message: res.data.msg,
                type: 'success'
            })
            clearAdd()
            getDevices()
        })
    }
}
const edit = (item) => {
    console.log(item)
    addFromItem.value = item
    addModelShow.value = true
}
</script>

<style lang="scss">
.iotdevice-list {
    display: flex;
    height: 100%;
    position: relative;

    .left {
        width: 400px;
        padding-top: 0;
        padding-bottom: 0;
        height: 100%;
        overflow-y: auto;
        margin: 0 10px 0 0;
    }

    .right {
        flex: 1;
        padding-top: 0;
        padding-bottom: 0;
        height: 100%;
        overflow-y: auto;

        .pagination {
            display: flex;
            flex-direction: row-reverse;
            margin-top: 30px;
        }
    }
}
</style>
